<?php
class PurchaseAction extends CommonAction {

    public function index()
    {
        $purchase = M('Purchase');
        $purchaseData = $purchase->order('purchase_date desc')->select();
        $allDate = array();

        foreach($purchaseData as $k=>&$v)
        {
            $allDate[] = $v['purchase_date'];
        }

        if(!isset($_GET['date']))
        {
            $lastPurchase = $purchase->order('purchase_date desc')
                                     ->limit(1)
                                     ->find();
            $date = $lastPurchase['purchase_date'];
        }
        else
        {
            $lastPurchase = $purchase->order('purchase_date desc')
                                     ->where("purchase_date='$_GET[date]'")
                                     ->limit(1)
                                     ->find();
            $date = $_GET['date'];
        }

        $lastPurchase['purchase_content'] = unserialize($lastPurchase['purchase_content']);
        $stuffs = array();
        $priceCount = 0;
        foreach($lastPurchase['purchase_content'] as $k=>$v)
        {
            $priceCount += $v['price_count'];

            foreach($v['stuff'] as $k2=>$v2)
            {
                $stuffs[] = $v2;
            }
        }

        foreach($stuffs as $k=>&$v)
        {
            foreach($stuffs as $k2=>&$v2)
            {
                if($v[0] == $v2[0] && $v[5] != $v2[5])
                {
                    $v[2] += $v2[2];
                    unset($stuffs[$k2]);
                }
            }
        }

        $this->assign(
            array(
                'allDate' => $allDate,
                'lastPurchase' => $lastPurchase,
                'stuffs' => $stuffs,
                'priceCount' => $priceCount,
                'date' => $date,
            )
        );

        $this->display();
    }


    public function enter($id)
    {
        $purchase = M('Purchase');
        $enter = M('Enter');

        $purchaseData = $purchase->where('id='.$id)->find();

        $data['id'] = $id;
        $data['is_enter'] = 1;

        $enterData['enter_content'] = $purchaseData['purchase_content'];
        $enterData['enter_date'] = $purchaseData['purchase_date'];

        if($purchase->save($data) && $enter->add($enterData))
            $this->success('入库成功，请查看入库单', __URL__.'/index');
    }
}